package com.lzh.crm.controller;

import com.alibaba.excel.EasyExcel;
import com.lzh.crm.pojo.Result;
import com.lzh.crm.pojo.User;
import com.lzh.crm.service.UserService;
import com.lzh.crm.utils.JwtUtil;
import com.lzh.crm.utils.Md5Util;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    //注册
    @PostMapping("/register")
    public Result register(@Valid User user) {
        //查询用户
        User u = userService.findByUserName(user.getUserName());
        //注册
        if(u == null){
            //没被占用
            userService.register(user);
            return Result.success();
        }
        else{
            //被占用
            return Result.error("用户名已被占用");
        }
    }

    //登录
    @PostMapping("/login")
    public Result<String> login(@Valid User user){
        //查询用户
        User u = userService.findByUserName(user.getUserName());

        //判断用户是否存在
        if(u == null){
            return Result.error("用户名错误");
        }

        //判断密码是否正确
        if(Md5Util.getMD5String(user.getPassword()).equals(u.getPassword())){
            //密码正确
            Map<String,Object> claims = new HashMap<>();
            claims.put("userId",u.getUserId());
            claims.put("userName",u.getUserName());
            claims.put("role",u.getRole());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }

        return Result.error("密码错误");
    }

    //增加信息
    @PostMapping("/insert")
    public Result insert(@RequestBody @Valid User user){
        User u = userService.findByUserName(user.getUserName());
        if(u == null){
            userService.insert(user);
            return Result.success("添加成功");
        }
        return Result.error("该用户已存在,添加失败");
    }

    //删除信息
    @DeleteMapping("/delete")
    public Result delete(Integer userId){
        userService.delete(userId);
        return Result.success("删除成功");
    }


    //更新信息
    @PutMapping("/update")
    public Result update(@RequestBody User user){
        userService.update(user);
        return Result.success("更新成功");
    }

    //查询所有信息
    @GetMapping("/selectAll")
    public Result<List<User>> selectAll() {
        List<User> u =  userService.selectAll();
        return Result.success(u);
    }

    //查询所需信息
    @GetMapping("/selectNeed")
    public Result<List<User>> selectNeed(User user){
        List<User> u =  userService.selectNeed(user);
        return Result.success(u);
    }

    @GetMapping("/info")
    public Result<User> info(@RequestHeader(name = "Authorization")  String token){
        Map<String, Object>map = JwtUtil.parseToken(token);
        String userName = (String)map.get("userName");
        User user = userService.findByUserName(userName);
        return Result.success(user);
    }

    //导出信息
    @GetMapping("/export")
    public void exportUser(HttpServletResponse response) throws IOException {
        List<User> userList = userService.select();

        //设置响应头（解决中文乱码 & 触发下载）
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("用户信息表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");

        //自动根据User类的字段和@ExcelProperty注解生成表头
        EasyExcel.write(response.getOutputStream(), User.class).sheet("用户数据").doWrite(userList);
    }

    //导入信息
    @PostMapping("/input")
    public Result input(@RequestParam("file") MultipartFile file) throws IOException {
            //EasyExcel自动根据User的注解映射表头和字段
            List<User> dtoList = EasyExcel.read(file.getInputStream()).head(User.class).sheet().doReadSync();

            //DTO转换为实体类、触发校验、密码加密
            List<User> userList = userService.convertExcelDTOToUser(dtoList);

            //插入数据库
            userService.saveBatch(userList);

            return Result.success();
    }
}
